<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Constructor</title>
  <meta
 content="C++ Tutorial: Constructor"
 name="description" />
  <meta
 content="C++ Tutorial, Constructor, Default Constructor, Copy Constructor, Destructor, Copy Assignment Operator, virtual destructor"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>

</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>

<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Constructor</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br />
<br />
<img src="images/constructor/BakRyungDo.png" alt="BakRyungDo"/>
<br />
<br />

<div class="bodytext" style="padding: 12px;" align="justify">

<div class="subtitle" id="Constructor">Constructor</div>
<p>Most of the class we write will have one or more constructors, a destructor and a copy assignment operator.</p>
<p>In this section, we'll have an example looks a little bit complicated. After we briefly study what the C++ compiler does for us, we'll be back to this example again.</p>
<p>Let's look at the following code:</p>
<pre>
//stringbuilder.h
#include &lt;iostream&gt;

class StringBuilder
{
private:
	static int counter;
	char *str;
public:
	<font color="red">StringBuilder();</font>
	<font color="red">StringBuilder(const char *);</font>
	~StringBuilder();
	const char *getString();
};

//stringbuilder.cpp
#include &lt;cstring&gt;
#include "stringbuilder.h"

int StringBuilder::counter = 0;

StringBuilder::StringBuilder()
{
	const char *defaultStr = "Default String";
	int len = std::strlen(defaultStr);
	str = new char[len + 1];
	std::strcpy(str,"Default String");
	counter++;
	std::cout <<"Default Constructor counter=" << counter << std::endl;
}

StringBuilder::StringBuilder(const char *s)
{
	int len = std::strlen(s);
	str = new char[len + 1];
	std::strcpy(str,s);
	counter++;
	std::cout <<"Constructor counter=" << counter << std::endl;
}

StringBuilder::~StringBuilder()
{
	counter--;
	std::cout <<"Destructor counter=" << counter << std::endl;
	delete [] str;
}

const char* StringBuilder::getString()
{
	return str;
}

//driver.cpp
#include &lt;iostream&gt;
#include "stringbuilder.h"

int main()
{
	StringBuilder myStringA;  //default constructor
	StringBuilder myStringB("StringB");  //constructor taking const char *
	StringBuilder *myStringC = new StringBuilder("StringC");  
	//StringBuilder myStringD = myStringC;  //copy constructor

	std::cout << "myStringA.str = " << myStringA.getString() << std::endl;
	std::cout << "myStringB.str = " << myStringB.getString() << std::endl;
	std::cout << "myStringC->str = " << myStringC->getString() << std::endl;
	//std::cout << "myStringD.str = " << myStringD.getString() << std::endl;

	delete myStringC;
	return 0;
}
</pre>
<p>The output should look like this:</p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
myStringA.str = Default String
myStringB.str = StringB
myStringC->str = StringC
Destructor counter=2
Destructor counter=1
Destructor counter=0
</pre>
<p>Constructor and destructor are each called 3 times as we expected.</p>
<p>Note that we have a pair of <strong>new[]</strong> and <strong>delete[]</strong> in the two constructors and in the destructor.</p>  
<pre>
int len = std::strlen(defaultStr);
str = new char[len + 1];
....
delete [] str;
</pre>

<p>We use <strong>new</strong> to allocate space to hold the string, and then we assign the address of the new 
memory to the <strong>str</strong> member. Here, the <strong>strlen()</strong> returns the length of a string 
not including the null. So we add one to the length.</p>
<p>Also note that the string is not stored in the object. The string is stored separately and the object 
just stores the address pointing where to locate the string.</p>
<p>The <strong>delete[]</strong> is necessary. When <strong>StringBuilder</strong> object expires, 
the <strong>str</strong> pointer expires. But the memory allocated with <strong>new[]</strong> 
to which <strong>str</strong> pointed remains allocated unless we use <strong>delete[]</strong> to free it. 
Deleting an object frees the memory for the object itself, 
but it does not free memory pointed to by pointers that were object members. 
Because of it, we should use the destructor. By placing the <strong>delete[]</strong> in the destructor, 
we ensure the memory that a constructor allocates with <strong>new[]</strong> is freed when the object goes away.</p>
<p>The compiler runs a constructor whenever an object of the type created:</p>
<pre>
StringBuilder myStringA;
StringBuilder myStringB("StringB");  
StringBuilder *myStringC = new StringBuilder("StringC");  
</pre>
<p>In the 2nd and 3rd cases, the constructor which takes a <strong>const char *</strong> 
are run to initialize the variable <strong>str</strong>. In the 3rd case, a new <strong>StringBuilder</strong> 
object is allocated dynamically. If everything goes well, all objects are initialized by running constructors. 
The first case, it is using default constructor.</p>
<br />
<br />


<div class="subtitle" id="MemberFunctions">Implicit C++ Member Functions </div>
<p>What implicit member functions are provided by C++?</p>
<p>To begin with, let's make the simplest class:</p>
<pre>
class Empty{};
</pre>
<p>Thanks to C++ compiler, actually it becomes something like this:</p>
<pre>
class Empty
{
public:
	Empty(){}				//default constructor
	Empty(const Empty&){}			//copy constructor
	~Empty(){}				//destructor
	Empty& operator=(const Empty&){}	//copy assignment operator
};
</pre>
<p>Isn't it convenient and amazing?</p>
<p>The member functions are called only when it's necessary.<br />
Let's see when they are called.</p>
<pre>
	Empty emptyA;				//default constructor
						//destructor
	Empty emptyB(emptyA);			//copy constructor
	emptyB = emptyA;			//copy assignment operator
</pre>
<br />
<br />




<div class="subtitle" id="Constructor">Constructor Initialization</div>
<p>A constructor is similar to a function. It has a name, a parameter list, and a function body. 
However, unlike a function, a constructor may also have a constructor <strong>initializer list</strong>.</p>
<pre>
#include &lt;iostream&gt;
#include &lt;string&gt;
using namespace std;

class Student
{
public:
	enum {Freshman = 1, Sophomore, Junior, Senior};
	Student(){}

	Student(const string &fn, const string &ln, int i, int y = Freshman)
		<font color="red">:first_name(fn), last_name(ln), id(i), year(y)</font>
	{
		cout << "Name: " << first_name << " " << last_name << endl;
		cout << "id  : " << id << endl;
		cout << "year  : " << year << endl;
	}

private:
	const string first_name;
	const string last_name;
	int id;
	int year;
};

int main()
{
	Student s1("John","Doe", 12345, Student::Junior);
	return 0;
}
</pre>
<p>The constructor initializer starts with a colon. It is followed by a comma-separated list of data members each of which 
is followed by an initializer inside parentheses:</p>
<pre>
Student(const string &fn, const string &ln, int i, int y = Freshman)
	<font color="red">: first_name(fn), last_name(ln), id(i), year(y) </font>
</pre>
<p>The constructor initializes the <strong>first_name</strong> to the value of its <strong>fn</strong> parameter, 
<strong>last_name</strong> to the value of its <strong>ln</strong>, and so on. As with any member function, 
constructors can be defined inside or outside of the class. The constructor initializer is specified only 
on the constructor definition, not its declaration. </p>
<p>One of the primary reasons constructor initializers are hard to understand is that it is usually legal to omit 
the initializer list and <strong>assign</strong> values to the data members inside the constructor body. So, we can re-write 
the code as following:</p>
<pre>
Student(const string &fn, const string &ln, int i, int y = Freshman)  {
	first_name = fn;
	last_name = ln;
	id = i;
 	year = y; 
}
</pre>
<p>This constructor in the new code assigns the members of class Student. It does not explicitly initialize them. 
Whether there is an explicit initializer or not, the <strong>first_name</strong> and <strong>last_name</strong> members are initialized 
even before the constructor is executed. This constructor implicitly uses the default <strong>string</strong> constructor to 
initialize the <strong>first_name</strong> and <strong>last_name</strong> members. When the body of the constructor is 
executed, the  <strong>first_name</strong> and <strong>last_name</strong> members already have values. Those values are overwritten by 
the assignment inside the constructor body.</p>
<p>Execution of constructor is done in two phases:</p>
<ol>
	<li>The initialization phase </li>
	<li>Body execution phase which consists of all the statements within the body of constructor. 
Note that data members of class type are <strong>always</strong> initialized in the initialization phase, 
regardless of whether the member is initialized explicitly in the constructor initializer list.
Initialization happens <strong>before</strong> any the statement execution of the constructor body.</li>
</ol>
<p>The members that are not initialize by the explicit initializer of the constructor are initialized using the rules for 
initializing variables. In other words, data members of class type are initialized by running the type's default constructor. 
The initial value of members of built-in or compound type depend on the scope of the object: Members of local scope are uninitialized, 
and members of global scope are initialized to 0.</p>
<p>The end results of the two are the same. The difference is that the version that uses the constructor initializer 
<strong>initializes</strong> values to the data members. The version that does not define a constructor initializer 
<strong>assigns</strong> values to the data members in the body of the constructor.  How significant is this distinction? 
It depends on the type of the data member.</p>
<p>If an initializer is not provided for a class member, then the compiler implicitly uses the default constructor for the member's type. 
However, if that class does not have a default constructor, then the attempt by the compiler to use it will fail. In such cases, 
an initializer must be provided in order to initialize the data member.</p>
<p>Some members <strong>must</strong> be initialized in the constructor initializer. For such members, assigning to them in the 
constructor body doesn't work. In other words, members of a class type that do not have a default constructor and members that are <strong>
const</strong> or <strong>reference</strong> types <strong>must</strong> be initialized in the constructor initializer.</p>
<p>Let's run the following example:</p>
<pre>
#include &lt;iostream&gt;
#include &gt;string&gt;
using namespace std;

class Student
{
public:
	Student(int id)
	{
		studentId = id;
		ss = id;
		rStudentId = studentId;
	}

private:
	int studentId;
	<font color="red">const int ss;
	int &rStudentId;</font>
};

int main()
{
	Student s1(12345);
	return 0;
}
</pre>
<p>Then, we'll get the errors like this:</p>
<pre>
'Student::ss' : must be initialized in constructor base/member initializer list
'Student::rStudentId' : must be initialized in constructor base/member initializer list
l-value specifies const object
</pre>
<p>By the time the constructor body begins executing, initialization is complete. So, the only time we can 
initialize <strong>const</strong> or <strong>reference</strong> data members is to use the constructor initializer:</p>
<pre>
Student(int id) : studentId(id), ss(id), rStudentId(studentId) {}
</pre>
<p>For most of the cases, the difference between initialization and assignment is a matter of efficiency. In other words,
a data member is initialized and assigned when it could have been initialized directly. The more important than the issue 
of efficiency is that some members of a class must be initialized. </p>
<p>Remember that we must use an initializer for any <strong>const</strong> or <strong>reference</strong> member. </p>

<br />
<br />




<div class="subtitle" id="CopyConstructor">Copy Constructor</div>
<p>There are cases when an object is copied automatically for us. This happens when an object is:</p>
<ul>
	<li>Passed by value to a function</li>
	<li>Returned from a function</li>
	<li>Initialized to another object through an initializer</li>
	<li>Provided a s a single argument to the object's constructor</li>
</ul>
<p>The copying is done by a special member function called the <strong>copy constructor</strong>. If we don't write one of our own, a default copy constructor is supplied for us. The default copy constructor simply copies the value of each data member to data members of the same name in the new object. In other words, it does a <strong>member-wise copy</strong>.</p>
<p>If we run the code in the first section after uncomment the lines of driver.cpp:</p>
<pre>
StringBuilder myStringD = myStringC; 
  ...
std::cout << "myStringD.str =" << myStringD.getString() << std::endl;
</pre>
<p>with disabled line in the destructor:</p>
<pre>
//delete [] str;
</pre>

<p>Then, we'll have the following output:</p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
myStringA.str = Default String
myStringB.str = StringB
myStringC.str = StringC
myStringD.str = StringC
Destructor counter=2
Destructor counter=1
Destructor counter=0
Destructor counter=-1
</pre>
<p>We thought we have created 3 objects but the destructor called 4 times. Why?</p>
<p>When we do either<br />
<pre>
StringBuilder myStringD = myStringC;
</pre>
as in the code or <br />
<pre>
StringBuilder myStringD = StringBuilder(myStringC);
</pre>
which is doing the same thing. 
</p>
<p>The compiler generates a copy constructor for us and it looks like this: </p>
<pre>
StringBulider(const StringBuilder &);
</pre>
<br />
<p>But because the compiler generated constructor does not increment the counter, we do not have the correct number of using <strong>new[]</strong>. Thus, to fix the counting problem, we need to make our customized copy constructer to do it.</p>
<p>Here is our new try for the copy constructor:</p>
<pre>
StringBuilder::StringBuilder(const StringBuilder & s)
{
	str = s.str;
	counter++;
	std::cout <<"Copy Constructor counter=" << counter << std::endl;
}
</pre>
<p>Let's run the code while keeping the "delete []" disabled.</p>
<p>We get the following output:</p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
Copy Constructor counter=4
myStringA.str = Default String
myStringB.str = StringB
myStringC.str = StringC
myStringD.str = StringC
Destructor counter=3
Destructor counter=2
Destructor counter=1
Destructor counter=0
</pre>
<p>It looks good. We fixed the mismatch problem between constructor and destructor. Constructors are called 4 times and destructor is called 4 times.</p>
<p>Now, try to run after activating the "delete[] str" of the destructor:</p>
<pre>
StringBuilder::~StringBuilder()
{
	counter--;
	std::cout <<"Destructor counter=" << counter << std::endl;
	delete [] str;
}
</pre>
<p>Still, we have another problem even though we fixed the counting bug. In my compiler (Visual Studio 2005), I get "Debug Assertion Failed!" error with the following output: </p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
Copy Constructor counter=4
myStringA.str = Default String
myStringB.str = StringB
myStringC.str = StringC
myStringD.str = StringC
Destructor counter=3
Destructor counter=2
</pre>
<p>So, it seems we should do more to our copy constructor than just incrementing the counter.</p>
<p>Actually, what the copy constructor does is so called <strong>shallow copy</strong>, copying a member one by one: </p>
<pre>
myStringD.str = myStringC.str; 
</pre>
<p>Note that both of the <strong>str</strong> pointers are pointing to the same location in memory. So, after one of the objects (myStringC) expires the destructor of that object free the memory using <strong>delete []</strong>, at the moment when the copied object(myStringD) try to free the memory, it's already gone. This results in undefined behavior.</p> 
<p>So, the cure for the problem is to make a <strong>deep copy</strong>. That is, rather than just copy the address of the string, the copy constructor should duplicate the string and assign the address of the duplicate to the <strong>str</strong> member. That way, each object gets its own string rather than referring to another object's string. As a result, each destructor call frees a different string rather than making duplicate attempts at freeing the same string.</p>
<p>Here is our new constructor.</p>
<pre>
StringBuilder::StringBuilder(const StringBuilder & s)
{
	int len = std::strlen(s.str);
	str = new char[len + 1];
	std::strcpy(str,s.str);
	counter++;
}
</pre>
<p>We have a new output. This time it looks ok.</p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
Copy Constructor counter=4
myStringA.str = Default String
myStringB.str = StringB
myStringC.str = StringC
myStringD.str = StringC
Destructor counter=3
Destructor counter=2
Destructor counter=1
Destructor counter=0
</pre>
<br />
<p>Files used for the example,  
<a href="../Files/cplusplus/constructor.zip">constructor.zip</a> <br /></p>
<br />
<br />


<div class="subtitle" id="AssgnmentOperator">Copy Assignment Operator</div>
<p>When we assign one object to another <strong>existing</strong> object, the assignment operator is used as we saw in the previous section <a href="constructor.html#MemberFunctions">Implicit C++ Member Functions</a>:</p>
<pre>
	Empty emptyA;
	Empty emptyB(emptyA);	
	emptyB = emptyA;
</pre>
<p>When we do:
<pre>
	emptyB = emptyA;
</pre>
<p>we are assigning <strong>emptyA</strong> object to <strong>emptyB</strong> object which is already exists.</p>
<p>Let's trigger the assignment operator by modifying our example a little bit.</p>
<p>Add the following two lines at the end of the driver.cpp.</p>
<pre>
	myStringD = myStringA;
	std::cout << "myStringD.str = " << myStringD.getString() << std::endl;
</pre>
<p>So, the code should look like this:</p>
<pre>
#include &lt;iostream&gt;
#include "stringbuilder.h"

int main()
{
	StringBuilder myStringA;  //default constructor
	StringBuilder myStringB("StringB");  //constructor taking const char *
	StringBuilder myStringC("StringC");  
	StringBuilder myStringD = myStringC;  // copy constructor

	std::cout << "myStringA.str = " << myStringA.getString() << std::endl;
	std::cout << "myStringB.str = " << myStringB.getString() << std::endl;
	std::cout << "myStringC.str = " << myStringC.getString() << std::endl;
	std::cout << "myStringD.str = " << myStringD.getString() << std::endl;

	myStringD = myStringA;
	std::cout << "myStringD.str = " << myStringD.getString() << std::endl;

	return 0;
}
</pre>
<p>Here, we are assigning <strong>myStringC</strong> object to <strong>myStringD</strong> object.<br />
If we run the code, we'll get the error, "Debug Assertion Failed!" with the following output:</p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
Copy Constructor counter=4
myStringA.str = Default String
myStringB.str = StringB
myStringC.str = StringC
myStringD.str = StringC
myStringD.str = StringA
Destructor counter=3
Destructor counter=2
</pre>
<p>This is almost the same result as we got for the case of copy constructor example.</p>
<p>This problem is caused by the inappropriate default assignment operator. So, we need to use our own assignment operator which makes a deep copy. The implementation is similar to the copy constructor, but there are some differences:</p>
<ul>
	<li>Because the target object may already refer to previously allocated data, the overload operator should use <strong>delete []</strong> to free the memory.</li>
	<li>The operator function should protect against assigning an object to itself. </li>
	<li>The operator function returns a reference to the invoking object. </li>
</ul>
<p>Here is our new assignment operator.</p>
<pre>
/* StringBuilder.cpp */
/* Copy Assignment Operator */
StringBuilder & StringBuilder::operator=(const StringBuilder & s)
{
	if(this == &s)
		return *this;
	delete [] str;
	int len = std::strlen(s.str);
	str = new char[len + 1];
	std::strcpy(str,s.str);
	return *this;
}

/* StringBuilder.h */
StringBuilder & operator=(const StringBuilder &);
</pre>
<p>Let's look at the implementation.<br />
<p>We check for self-assignment by examining if the address of the right-hand side of the assignment, <strong>&s</strong>, is the same as the address of the receiving object, <strong>this</strong>.</p>
<p>If the given object is not the receiving object itself, we free the memory that <strong>str</strong> pointed to. The reason for this is that shortly after <strong>str</strong> will be assigned the address of a new string. If we don't first apply the <strong>delete[]</strong> operator, the previous string will remain in memory and we have a memory leak. </p>
<p>Then, the code does like a copy constructor, allocating enough space for the new string and then copying the string from the right-hand side object to the new location.</p>
<p>Finally, it returns <strong>*this</strong>.</p>
<p>This will fix our problem.</p>
<p>Here is the output which looks fine.</p>
<pre>
Default Constructor counter=1
Constructor counter=2
Constructor counter=3
Copy Constructor counter=4
myStringA.str = Default String
myStringB.str = StringB
myStringC.str = StringC
myStringD.str = StringC
myStringD.str = Default String
Destructor counter=3
Destructor counter=2
Destructor counter=1
Destructor counter=0
</pre>

<br />
<p>Files used for the example,  
<a href="../Files/cplusplus/assignmentoperator.zip">assignmentoperator.zip</a> <br /></p>
<br />
<br />

<br />
<br />


<div class="subtitle" id="copy">Shallow Copy vs. Deep Copy</div>
<p>What's the difference between deep copy and shallow copy?</p>
<p>Let's look at the following code.</p>
<pre>
#include &lt;iostream&gt;
using namespace std;

struct Copy
{
	char *ptr;
};
 
void ShallowCopy(Copy &src, Copy &dest)
{
	dest.ptr = src.ptr;
	int dum = 1;
}

void DeepCopy(Copy &src, Copy &dest)
{
	dest.ptr = new char[strlen(src.ptr)+1];
	memcpy(dest.ptr, src.ptr, strlen(src.ptr)+1);
}

int main()
{
	struct Copy src;
	struct Copy dest;
	src.ptr = strdup("Beethoven");

	cout << "Shallow Copy" << endl;
	ShallowCopy(src,dest);
	cout << "dest.ptr =" << dest.ptr << endl;
	cout << "source changed" << endl;
	src.ptr[0] = 'b';
	cout << "src.ptr =" << src.ptr << endl;
	cout << "dest.ptr =" << dest.ptr << endl;

	cout << endl;
	cout << "Deep Copy" << endl;
	DeepCopy(src,dest);
	cout << "dest.ptr =" << dest.ptr << endl;
	cout << "source changed" << endl;
	src.ptr[8] = 'N';
	cout << "src.ptr =" << src.ptr << endl;
	cout << "dest.ptr =" << dest.ptr << endl;
}
</pre>
<p>Output from the run:</p>
<pre>
Shallow Copy
dest.ptr =Beethoven
source changed
src.ptr =beethoven
dest.ptr =beethoven

Deep Copy
dest.ptr =beethoven
source changed
src.ptr =beethoveN
dest.ptr =beethoven
</pre>
<p>As we see from the output, the pointers of <strong>dest</strong> and <strong>src</strong> are pointing to the same address for shallow copy while they are using different address space for deep copy.</p>
<p>The shallow copy may cause a lot of run-time errors, especially with the creation and deletion of object. Shallow copy should be used very carefully and only when a programmer really understands what he wants to do. In most cases, shallow copy is used when there is a need to pass information about a complex structure without actual duplication of data. We must also be careful with destruction of shallow copy.</p>
<p>Actually, shallow copy is rarely used. There is a <strong>smart pointer</strong> that, in some cases, is an enhancement of the shallow copy concept.</p>
<p>Deep copy should be used in most cases, especially for the cases when the size of the copied structure is small.</p>
<br />
<br />



<div class="subtitle" id="ctordtor">How does C++ deal with constructors and destructors of a class and its child (derived) class?</div>
<p><strong>Constructor</strong> </p>
<ul>
	<li>The base class object is constructed first. This means the base class object should be constructed first before the program enters the body of the child class constructor. We use the <strong>member initializer list</strong> to accomplish this. But if we omit calling a base class constructor, the program uses the default base class constructor. <strong>A child class constructor always calls a base class constructor</strong>.</li>
	<li>The child class should pass base class information via base class constructor.</li>
	<li>The child class constructor should initialize its member.</li>
	<li>A child class doesn't inherit the base class constructor.</li>
</ul>
<p><strong>Destructor</strong> </p>
<ul>
	<li>If we create automatic storage class object, its destructor is called automatically called when the program exits.</li>
	<li>If the object is created by using <strong>new</strong>, it resides in heap memory (free store), its destructor is called automatically when we use <strong>delete</strong> to free the memory.</li>
	<li>If we create a static storage class object, its destructor is called automatically when the program exits.</li>
	<li>If we create temporary objects, the destructors for the objects are called when we finished using them.</li>
	<li>When we delete a child object, the destructor for the child is called and then the destructor for the base is called.</li>
	<li>A base class destructor should be <strong>virtual</strong> unless the class isn't to be used as a base class. That way, when we delete a child class via base class pointer (or reference) to the object, the program uses the child class destructor followed by the base class destructor rather than using only the base class destructor. More on <a href="virtualfunctions.html" target="_blank">Virtual Functions</a>.</li>
	<li>A child class doesn't inherit the base class destructor.</li>
	<li>When a program deletes an object, it first calls the child class destructor and then the base class destructor.</li>
</ul>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Checking
{
public:
	Checking(int bal = 0, int i = 100) {
		cout << "Checking constructor" << endl;
		balance = bal;
		id = i;
	}

	~Checking() {
		cout << "Checking destructor" << endl;
	}

	int getBalance() {
		return balance;
	}

	int getId() {
		return id;
	}
private:
	int balance;
	int id;
};

class InterestChecking : public Checking
{
public:
	InterestChecking(float r, int b, int i) : Checking(b, i) {
		cout << "InterestChecking constructor A" << endl;
		rate = r;
	}

	// copy constructor for the base class will be called
	InterestChecking(float r, const Checking &chk) : Checking(chk) {
		cout << "InterestChecking constructor B" << endl;
		rate = r;
	}

	// An alternative version
	/*
	IntersetChecking(const Checking &chk, float r) : Checking(chk), rate(r) {
	}
	*/

	~InterestChecking() {
		cout << "InterestChecking destructor" << endl;
	}

	float getRate() {
		return rate;
	}
private:
	float rate;
};

int main()
{
	cout << "Normal Checking..." << endl;
	Checking *c1 = new Checking(1000, 101);
	delete c1;

	cout << endl;
	cout << "Interest Checking..." << endl;
	InterestChecking *c2 = <font color="red">new</font> InterestChecking(5.9, 5000, 102);
	<font color="red">delete</font> c2;

	cout << endl;
	cout << "Interest Checking using Checking pointer..." << endl;
	<font color="red">Checking *c3;
	c3 = new InterestChecking(8.9, 25000, 103);
	delete c3;</font>

	return 0;
}
</pre>
<p>The output clearly shows that the base constructor is called first when we make a child object and the child destructor is called first when we delete a child object.</p>
<pre>
Normal Checking...
Checking constructor
Checking destructor

Interest Checking...
Checking constructor
InterestChecking constructor A
InterestChecking destructor
Checking destructor

Interest Checking using Checking pointer...
Checking constructor
InterestChecking constructor A
<font color="red">Checking destructor</font>
</pre>
<p>The last output, however, does not call the child class destructor. It only calls the base class constructor. That's because we're using a pointer to the base class.</p>
<p>If we had used <strong>virtual destructor</strong>,</p>
<pre>
virtual ~Checking() {
	cout << "Checking destructor" << endl;
}
</pre>
<p>the child class destructor would have been called:</p>
<pre>
Normal Checking...
Checking constructor
Checking destructor

Interest Checking...
Checking constructor
InterestChecking constructor A
InterestChecking destructor
Checking destructor

Interest Checking using Checking pointer...
Checking constructor
InterestChecking constructor A
<font color="red">InterestChecking destructor</font>
Checking destructor
</pre>
<p>More on <a href="virtualfunctions.html" target="_blank">Virtual Functions</a></p>


<div id="rightpanel">
<div align="center">
</div></div>

<br />
<br />
<img src="images/constructor/HongDo.png" alt="HongDo"/>
<br />
<br />

<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />




<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
